package cn.craftyun.yunexam.service.impl;

import cn.craftyun.yunexam.entity.ExamAnswer;
import cn.craftyun.yunexam.mapper.ExamAnswerMapper;
import cn.craftyun.yunexam.service.ExamAnswerService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service
public class ExamAnswerServiceImpl extends ServiceImpl<ExamAnswerMapper, ExamAnswer> implements ExamAnswerService {
    @Resource
    private ExamAnswerService examAnswerService;

    @Override
    public int getExamScore(Long examId, Long userId) {
        Wrapper<ExamAnswer> wrapper = new QueryWrapper<ExamAnswer>()
                .eq("user_id", userId)
                .eq("exam_id", examId)
                .select("coalesce(sum(answer_score),0) as total_score");
        List<Map<String, Object>> scoreMap = getBaseMapper().selectMaps(wrapper);
        return ((BigDecimal) scoreMap.get(0).get("total_score")).intValue();
    }

    @Override
    public List<ExamAnswer> getExamAnswer(Long examId, Long userId) {
        Wrapper<ExamAnswer> queryExamAnswerWrapper = new QueryWrapper<ExamAnswer>()
                .eq("user_id", userId)
                .eq("exam_id", examId);
        return examAnswerService.list(queryExamAnswerWrapper);
    }

    @Override
    public boolean removeByExamId(Long examId) {
        Wrapper<ExamAnswer> wrapper = new UpdateWrapper<ExamAnswer>().eq("exam_id", examId);
        return getBaseMapper().delete(wrapper) > 0;
    }

    @Override
    public boolean removeByUserId(Long userId) {
        Wrapper<ExamAnswer> wrapper = new UpdateWrapper<ExamAnswer>().eq("user_id", userId);
        return getBaseMapper().delete(wrapper) > 0;
    }

    @Override
    public boolean removeByPaperId(Long paperId) {
        return getBaseMapper().deleteByPaperId(paperId) > 0;
    }

    @Override
    public List<Map<String, Object>> getUserResult(Long examId, Long userId) {
        return getBaseMapper().getUserExamAnswer(examId, userId);
    }
}
